package client

import (
	"time"
	"ws-demo-go/internal/message/client"
	"ws-demo-go/internal/message/common"
	"ws-demo-go/pkg/logger"
	"ws-demo-go/pkg/str"
)

// 这个示例展示了如何连接到服务端并发送/接收消息

type Client struct {
	msgClient *client.Client // 消息层客户端
}

// NewBusinessClient 创建业务层客户端实例
func NewBusinessClient(serverAddr string, reconnect bool) *Client {
	bc := &Client{
		msgClient: client.NewClient(serverAddr, reconnect),
	}
	bc.msgClient.SetOnMessage(bc.onMessageMessage)
	return bc
}

// Connect 连接到服务端
func (bc *Client) Connect() error {
	return bc.msgClient.Connect()
}

// SendRequest 发送 Request 请求 TODO 或许应该把这个方法变成函数，客户端和服务端都能用，放在 common 包里面
func (bc *Client) SendRequest(payload interface{}) error {
	// 创建消息
	msg := common.NewMessage(payload)
	logger.Info("Sending message: %s", msg.MessageID)

	// 发送消息
	return bc.msgClient.SendMessage(msg)
}

// Close 关闭客户端连接
func (bc *Client) Close() {
	logger.Info("Closing business client connection...")
	bc.msgClient.Close()
}

// IsConnected 检查是否已连接
func (bc *Client) IsConnected() bool {
	return bc.msgClient.IsConnected()
}

// ExampleSendMessages 示例：发送一系列消息
func (bc *Client) ExampleSendMessages() {
	// 等待连接建立
	//time.Sleep(1 * time.Second)
	//
	//// 发送几条示例消息
	//for i := 1; i <= 5; i++ {
	// 检查是否已连接
	if !bc.IsConnected() {
		logger.Error("Not connected to server")
		return
	}
	var i = 1
	// 创建消息内容
	messageContent := map[string]interface{}{
		"id":        i,
		"content":   str.Sprintf("Hello, this is message #%d", i),
		"timestamp": time.Now().UnixMilli(),
	}

	// 发送消息
	if err := bc.SendRequest(messageContent); err != nil {
		logger.Error("Failed to send message: %v", err)
	}

	// 等待一秒再发送下一条消息
	time.Sleep(1 * time.Second)
	//}
}

func (bc *Client) onMessageMessage(msg *common.Message) {
	logger.Info("Received message from server, messageId: %s", msg.MessageID)
	logger.Info("Message payload: %v", msg.Payload)
}
